import React, { useState, useContext } from "react";
import { places } from "./data";
import { getImageUrl } from "../utils";
import { ImageSizeContext } from "./Context";
import { PlaceData } from "./interface";

function List() {
  const listItems = places.map(place => (
    <li key={place.id}>
      <PlaceImage place={place} />
      <MemoPlace place={place} />
    </li>
  ));
  return <ul>{listItems}</ul>;
}
interface PlaceProps {
  place: PlaceData;
}

const MemoPlace = React.memo(Place);

function Place({ place }: PlaceProps) {
  console.log("Place");

  return (
    <p>
      <b>{place.name}</b>
      {": " + place.description}
    </p>
  );
}
type PlaceImageProps = PlaceProps;
function PlaceImage({ place }: PlaceImageProps) {
  const imageSize = useContext(ImageSizeContext);
  return <img src={getImageUrl()} alt={place.name} width={imageSize} height={imageSize} />;
}

function Index() {
  const [isLarge, setIsLarge] = useState(false);
  const imageSize = isLarge ? 150 : 100;
  return (
    <ImageSizeContext.Provider value={imageSize}>
      <label>
        <input
          type="checkbox"
          checked={isLarge}
          onChange={e => {
            setIsLarge(e.target.checked);
          }}
        />
        Use large images
      </label>
      <hr />
      <List />
    </ImageSizeContext.Provider>
  );
}

export default Index;
